<template>
  <div>
    <div class="gva-search-box">
      <!-- 搜索框内容 -->
    </div>
    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button type="primary" icon="plus" @click="openDialog">
          新增
        </el-button>
      </div>
      <!-- 组件 -->
      <el-table
        :data="tableData"
        @sort-change="sortChange"
        @selection-change="handleSelectionChange"
      >

        <!-- <el-table-column align="left" label="ID" min-width="80" prop="ID" sortable="custom" /> -->
        <el-table-column
          align="left"
          label="服务名称"
          min-width="150"
          prop="ServiceName"
          sortable="custom"
        />
        <el-table-column
          align="left"
          label="服务配置"
          min-width="160"
          prop="ServiceConfig"
          :show-overflow-tooltip="true"
        >
          <template #default="scope">
            {{ parseServiceConfig(scope.row.ServiceConfig) }}
          </template>
        </el-table-column>




      <el-table-column align="left" label="创建时间" min-width="200" prop="CreatedAt" sortable>
          <template #default="scope">
            {{ formatDate(scope.row.CreatedAt) }}
          </template>

        </el-table-column>

        <el-table-column align="left" fixed="right" label="操作" width="200">
          <template #default="scope">
            <!--            <el-button type="primary" link @click="opendrawerVisible(scope.row)">-->
            <!--              编辑-->
            <!--            </el-button>-->
            <el-button type="primary" link @click="deleteApiFunc(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
          :current-page="page"
          :page-size="pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
    <el-drawer
      v-model="drawerVisible"
      title="新增节点"
      direction="rtl"
      :size="drawerSize"
      @close="resetForm"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="服务" prop="ServiceID">
          <el-select
            v-model="form.ServiceID"
            placeholder="请选择服务"
            style="width: 100%"
            @change="change"
          >
            <el-option
              v-for="(optionItem, optionIndex) in serviceData"
              :key="optionIndex"
              :label="optionItem.ServiceName"
              :value="optionItem.ServiceId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="服务配置" prop="ServiceConfig">
          <el-input v-model="form.ServiceConfig" placeholder="请输入服务配置" />
        </el-form-item>
<!--        <el-form-item label="开始时间" prop="StartTime">-->
<!--          <el-date-picker-->
<!--            v-model="form.StartTime"-->
<!--            type="datetime"-->
<!--            placeholder="请选择"-->
<!--            style="width: 100%"-->
<!--          />-->
<!--        </el-form-item>-->
        <el-button @click="drawerVisible = false"> 取消 </el-button>
        <el-button type="primary" @click="submitForm"> 确定 </el-button>
      </el-form>
    </el-drawer>
  </div>
</template>


<script setup>
import { ref, onMounted } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import {useRoute} from "vue-router";
import {
  getServiceConfigList,
  addServiceConfig,
  deleteServiceConfig,
  getServiceList,
} from "@/api/service"; // Replace with your API

const route = useRoute()
const page = ref(1);
const total = ref(0);
const pageSize = ref(10);
const tableData = ref([]);
const serviceData = ref([]);
const ServiceId =ref('')
const drawerVisible = ref(false);
const drawerSize = ref("40%");
const formRef = ref(null);
const form = ref({
  ServiceID: "",
  ServiceName: "",
  ServiceConfig: "",
  StartTime: "",
});
const rules = {
  ServiceID: [{ required: true, message: "请输入ID", trigger: "blur" }],
  ServiceConfig: [
    { required: true, message: "请输入服务配置", trigger: "blur" },
  ],
  StartTime: [{ required: true, message: "请选择开始时间", trigger: "change" }],
};

const opendrawerVisible = (row) => {
  form.value = {
    ServiceID: row.ServiceID,
    ServiceName: row.ServiceName,
    ServiceConfig: row.ServiceConfig,
    StartTime: new Date(row.StartTime), // Convert to Date object for date-picker
  };
  drawerVisible.value = true;
};
const change = (value) => {
  const isTrue = serviceData.value.find((list) => list.ServiceId === value);

  if (isTrue) {
    form.value.ServiceName = isTrue.ServiceName;
  } else {
    form.value.ServiceName = "";
  }
  console.log(form.value.ServiceName);
};
const getServiceData = async () => {
  try {
    const response = await getServiceList(-1, -1);
    if (response.code === 0) {
      serviceData.value = response.data.list;
    } else {
      ElMessage.error(response.msg || "获取数据失败");
    }
  } catch (error) {
    console.error("API Error:", error);
    ElMessage.error("获取数据失败");
  }
};
const getTableData = async () => {
  try {
    ServiceId.value = route.query.ServiceId || ''
    const response = await getServiceConfigList(page.value, pageSize.value,ServiceId.value);
    if (response.code === 0) {
      tableData.value = response.data.list.map((item) => ({
        ...item,
        StartTime: new Date(item.StartTime), // Convert to Date object for table display
      }));
      total.value = response.data.total;
    } else {
      ElMessage.error(response.msg || "获取数据失败");
    }
  } catch (error) {
    console.error("API Error:", error);
    ElMessage.error("获取数据失败");
  }
};

onMounted(() => {
  getTableData();
});

const openDialog = () => {
  form.value = {
    ServiceID: "",
    ServiceConfig: "",
    StartTime: new Date(), // Default to current time
  };
  drawerVisible.value = true;
  getServiceData();
};

const resetForm = () => {
  formRef.value.resetFields();
};

const formatDate = (date) => {
  if (date) {
    const d = new Date(date);
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, "0");
    const day = String(d.getDate()).padStart(2, "0");
    const hours = String(d.getHours()).padStart(2, "0");
    const minutes = String(d.getMinutes()).padStart(2, "0");
    const seconds = String(d.getSeconds()).padStart(2, "0");
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  }
  return "";
};

const parseServiceConfig = (config) => {
  try {
    const parsed = JSON.parse(config);
    return Object.entries(parsed)
      .map(([key, value]) => `${key}: ${value}`)
      .join(", ");
  } catch (e) {
    return config;
  }
};

const submitForm = async () => {
  try {
    await formRef.value.validate();
    const payload = {
      ServiceID: form.value.ServiceID,
      ServiceName: form.value.ServiceName,
      ServiceConfig: form.value.ServiceConfig,
      StartTime: form.value.StartTime.toISOString(), // Convert to ISO string format
    };
    await addServiceConfig(payload);
    ElMessage.success("添加成功");
    drawerVisible.value = false;
    getTableData();
  } catch (error) {
    console.error("Form Submit Error:", error);
    ElMessage.error("添加失败");
  }
};

const deleteApiFunc = (row) => {
  ElMessageBox.confirm("确认删除此配置？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      await deleteServiceConfig({ id: row.ID });
      ElMessage.success("删除成功");
      getTableData();
    } catch (error) {
      console.error("Delete Error:", error);
      ElMessage.error("删除失败");
    }
  });
};

const handleCurrentChange = (newPage) => {
  page.value = newPage;
  getTableData();
};

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  getTableData();
};

const sortChange = () => {
  // 处理排序逻辑
};
</script>


<style scoped>
.gva-search-box {
  margin-bottom: 20px;
}

.gva-table-box {
  margin-bottom: 20px;
}

.gva-btn-list {
  margin-bottom: 20px;
}

.gva-pagination {
  margin-top: 20px;
}
</style>
